package com.chen.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.exceptions.ClientException;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * ClassName: UploadUtil
 * Package: com.chen.utils
 * Description: 文件上传工具类
 *
 * @Author 陈俊辉
 * @Create 2024/4/12 1:00
 * @Version 1.0
 */
@Component
public class UploadUtil {

    //节点
    public static final String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    //仓库
    public static final String bucketName = "chen-itcast-web";
    //key
    public static final String key = "LTAI5tLZtE3MLCTYP9T9JqqM";
    //secret
    public static final String secret = "IL3DQGASx6cpKdBuPxMAezC2Gq6Ye4";

    public static String upload(MultipartFile file) throws IOException {


        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint,
                key, secret);
        //设置一个文件名字
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf('.'));

        //上传文件
        ossClient.putObject(bucketName, fileName, file.getInputStream());
        //返回URL路径
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;

        return url;
    }


}
